import Toast from "../../components/dist/toast/toast.js"
import { ShopModel } from '../../models/ShopModel.js'
let Shop = new ShopModel()
// 使用钱需要实例化才能使用

Page({
    data: {
        // 1、管理员 用户名密码
        account:"",
        password:"",
        // 2、用户输入 用户名密码
        accountV:'',
        passwordV:'',
        // 3、记住密码
        rememberPwd:false,
        admin:{},

    },
    onLoad: function (options) {
        this._init()
    },
    _init:function(){
        this._getAdminInfo()
        this.checkAutoLogin()
    },
    // 点击记住密码
    _rememberPwd:function(e){
        this.setData({
            checked:!this.data.checked
        })
    },
    // 获取管理员用户名和密码
    _getAdminInfo: async function(){
        let result = await Shop.getShop({})

        if(result.length > 0){
            this.setData({
                account:result[0].account,
                password:result[0].password
            })
        }
    },
   
    // 检查是否选择记住密码
    checkAutoLogin:function(){
        let admin = wx.getStorageSync('admin')
        if(admin){
            this.setData({
                accountV:admin.accountV,
                passwordV:admin.passwordV,
                checked:true
            })
        }else{
            console.log('no admin')
            this.setData({
                checked:false
            })
        }
    },
    // 选择记住密码后，将用户信息存储在缓存中
    _setStorage:function(evt){
        if(this.data.checked){
            let admin = {
                accountV:this.data.account,
                passwordV:this.data.password
            }
            wx.setStorageSync('admin', admin)
        }else{
            wx.removeStorage({
                key: 'admin',
                success (res) {
                }
              })
        }
    },
     // 输入用户名
     inputAccount:function(e){
        let accountV = e.detail
        this.setData({accountV})  
    },
    // 输入密码
    inputPassword:function(e){
        let passwordV = e.detail
        this.setData({
            passwordV:passwordV
        })
    }, 
    // 登录前进行校验
    _checkSubmit:function(){
        // 1、用户输入 用户名密码
        let accountV = this.data.accountV
        let passwordV = this.data.passwordV
        console.log('user',accountV,passwordV)
        // 2、管理员 用户名密码
        let account = this.data.account
        let password = this.data.password
        console.log('admin',account,password)
       if(accountV.length <= 0){
           return '用户名不能为空!'
       }
       if(passwordV.length <= 0){
           return '密码不能为空!'
       }
       if(!(account == accountV && password == passwordV)){
           return '用户名或密码输入错误!'
       }
       return ''
    },
    // 登录
    Submit:function(evt){
        let message =  this._checkSubmit()
        if(message.length > 0){
            Toast.fail(message)
            return
        }else{
            this._setStorage()
            wx.redirectTo({
                url: '../../AdminPackages/index/index'
            })
        }
    },
   
 
})